package com.lh.service.Impl;

import ch.qos.logback.classic.pattern.Util;
import com.lh.entity.Result;
import com.lh.entity.User;
import com.lh.mapper.UserMapper;
import com.lh.service.UserService;
import com.lh.utils.Md5Util;
import com.lh.utils.ThreadLocalUtil;
import org.apache.ibatis.annotations.Insert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
   @Autowired
    UserMapper userMapper;
    @Override
    public User findUserByName(String username) {
      User user=  userMapper.findUserByName(username);
        return user;
    }

    @Override
    public Result register(String username, String password) {
        String passwordMD5 = Md5Util.getMD5String(password);

       int i= userMapper.registerUser(username,passwordMD5);
        if(i>0){
            return new Result(0,"注册成功",null);
        }
        return new Result(0,"注册失败",null) ;
    }

    @Override
    public Result updateUser(User user) {
        user.setUpdateTime(LocalDateTime.now());
       int i= userMapper.updateUser(user);
       if(i>0){
           return Result.success("更新成功");
       }else{
           return Result.error("更新失败");
       }

    }

    @Override
    public Result updateAvatar(String imageURL) {
        Map<String,Object> usermap = ThreadLocalUtil.get();
        Integer id = (Integer) usermap.get("id");
      int i=  userMapper.updateAvatar(imageURL,id);
      if(i>0){
          return Result.success("头像更新成功");
      }
        return Result.error("头像更新失败");
    }

    @Override
    public Result updatePwd(String newPassword) {
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        int i=  userMapper.updatePwd(newPassword,username);
        if (i>0){
            return Result.success("密码更新成功");
        }else {
            return Result.error("密码更新失败");
        }
    }
}
